package com.hydra.wiki.util.spring;

import javax.servlet.ServletContext;

import com.hydra.wiki.core.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;


//读取配置文件进行加载
@Component
public class BeanFactory implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(BeanFactory.class);

    private static ApplicationContext applicationContext;

    /**
     * Get bean by bean name
     *
     * @param name bean name
     * @return bean
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * Get bean by bean type
     *
     * @param clazz class object
     * @param <T>   bean type
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * Get bean by bean name and bean type
     *
     * @param name  bean name
     * @param clazz class object
     * @param <T>   bean type
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * Get ApplicationContext
     *
     * @return application context
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (BeanFactory.applicationContext == null) {
            BeanFactory.applicationContext = applicationContext;
        }
    }

    /**
     * Get bean by bean type
     *
     * @param clazz class object
     * @param <T>   bean type
     * @return bean
     */
    public <T> T bean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
}
